"""
推荐学习资料
https://blog.csdn.net/songfreeman/article/details/50943603
"""

import pika
# 打开消息队列连接
from ...configread import MyConfigParser

MQUser = ""
MQPwd = ""

def Init(configPath=None):
    """
    读取配置文件里的用户等信息
    :param configPath:
    :return:
    """
    global MQUser, MQPwd, MQHost, MQVirtualHost
    if not configPath:
        raise ValueError('[-] Error: configPath must Have')
    cf = MyConfigParser(configPath).get_configparser().set_keep_keys_case().read_config().get_cf()
    MQUser = cf.get('mq', 'User')
    MQPwd = cf.get('mq', 'Pwd')
    MQHost = cf.get('mq', 'Host')
    MQVirtualHost = cf.get('mq', 'VirtualHost')


def OpenConnRabbitMQ(configPath=None):
    """
    连接到 RabbitMQ  返回连接
    :param configPath:
    :return:
    """
    print("OpenConnRabbitMQ ...")
    if not MQUser and not configPath:
        raise ValueError
    if not MQUser and configPath:
        Init(configPath)
    #创建一个新的明文凭证实例
    credentials = pika.PlainCredentials(MQUser, MQPwd)
    #创建一个新的参数实例。看到“参数”
    #可以通过将 heartbeat 设为 0，关闭 rabbitmq 的心跳检测
    parameters = pika.ConnectionParameters(host=MQHost,
                                           virtual_host=MQVirtualHost,
                                           credentials=credentials,
                                           heartbeat=0)
    ConnRabbitMQ = pika.BlockingConnection(parameters)  # 连接 RabbitMQ
    return ConnRabbitMQ


# 关闭消息队列
def CloseConnRabbitMQ(ConnRabbitMQ):
    print('CloseConnRabbitMQ ...')
    ConnRabbitMQ.close()


def callback(ch, method, properties, body):
    """
    接受消息的callback函数
    :param ch:
    :param method:
    :param properties:
    :param body:
    :return:
    """
    print(" [x] Received %r" % body)

